/**
 * Copyright 2019-2022 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "framework/graph/core/optimize/schedule/graph_optimize_scheduler.h"

#include "infra/base/assertion.h"
#include "infra/base/securestl.h"

#include "framework/graph/core/cgraph/compute_graph.h"

#include "framework/graph/core/optimize/schedule/graph_pass_list.h"

namespace hiai {
namespace {
class GraphOptimizeSchedulerImpl : public GraphOptimizeScheduler {
public:
    GraphOptimizeSchedulerImpl(GraphPassList& passList, size_t maxOptimizeLoopCount)
        : passList_(passList), maxOptimizeLoopCount_(maxOptimizeLoopCount)
    {
    }

    ~GraphOptimizeSchedulerImpl() override = default;

private:
    Status Schedule(ge::ComputeGraph& graph) override
    {
        for (size_t i = 0; i < maxOptimizeLoopCount_; i++) {
            auto status = passList_.Optimize(graph);
            if (status == OptimizeStatus::OPTIMIZE_FAILED) {
                return FAILURE;
            } else if (status == OptimizeStatus::OPTIMIZE_NOT_CHANGED) {
                return SUCCESS;
            }
        }

        return SUCCESS;
    }

private:
    GraphPassList& passList_;
    size_t maxOptimizeLoopCount_;
};
} // namespace

std::unique_ptr<GraphOptimizeScheduler> GraphOptimizeScheduler::Make(
    GraphPassList& passList, size_t maxOptimizeLoopCount)
{
    HIAI_EXPECT_TRUE_R(maxOptimizeLoopCount <= 3, nullptr);

    return make_unique_nothrow<GraphOptimizeSchedulerImpl>(passList, maxOptimizeLoopCount);
}
} // namespace hiai